package com.wanghua.spring.util;

import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.sax.SAXTransformerFactory;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.text.*;
import java.util.Random;

public class StringUtil {
    public static boolean isNull(Object obj) {
        return obj == null;
    }

    public static boolean isNull(String obj) {
        return obj == null || obj.trim().length() == 0;
    }

    public static String breakString(String ss, int length) {
        StringBuffer buffer = new StringBuffer();
        String[] words = ss.split(" ");
        int currLineLength = 0;
        for (String word : words) {
            if (currLineLength + word.length() > length) {
                buffer.append("\r\n").append(word);
                currLineLength = 0;
            } else {
                buffer.append(" " + word);
                currLineLength += word.length() + 1;
            }
        }
        return buffer.toString();
    }

    /**
     * 返回随机汉字
     */
    public static String getChineseCharacter(long seed) throws Exception {
        String str = null;
        int highPos, lowPos;
        Random random = new Random(seed);
        highPos = (176 + Math.abs(random.nextInt(39)));
        lowPos = 161 + Math.abs(random.nextInt(93));
        byte[] b = new byte[2];
        b[0] = (new Integer(highPos)).byteValue();
        b[1] = (new Integer(lowPos)).byteValue();
        str = new String(b, "GBK");
        return str;
    }

    public static String getURL(HttpServletRequest request) {
        String requestURI = request.getRequestURI();                     //注意：以双斜杠开头的
        String queryString = request.getQueryString();                   //获取所有参数
        String url = requestURI + "?" + filterQueryString(queryString); //过滤指定参数

        if (!url.endsWith("?"))
            url += "&";
        return url;
    }

    public static String filterQueryString(String queryString) {
        if (queryString == null)
            return "";

        queryString = queryString.replaceAll("[^&]*sort=[^&]*", "");   //过滤sort
        queryString = queryString.replaceAll("[^&]*order=[^&]*", "");   //过滤order
        queryString = queryString.replaceAll("[^&]*action=[^&]*", "");   //过滤action
        queryString = queryString.replaceAll("&{2,}", "&");  //过滤重复的&&
        queryString = queryString.replaceAll("^&", "");  //过滤开始字符&
        queryString = queryString.replaceAll("&$", "");  //过滤结束字符&

        return queryString;
    }

    /**
     * 从 URL 中获取搜索关键词，如果字符串为空，则返回null
     * 注意：Google采用的是UTF-8编码;Baidu使用的是GBK编码。JavaScript可以进行UTF-8编码、解码，但不能对GBK编码、解码。
     * Google搜索关键词是 q；Baidu搜索关键词是 wd或 word。
     */
    public static String getParameter(String url) {
        if (url == null || !url.contains("?"))
            return null;
        if (url.toLowerCase().contains("baidu.com")) {
            String value = getParameter(url, "wd");
            if (StringUtil.isNull(value)) {
                value = getParameter(url, "word");
                if (!StringUtil.isNull(value)) {
                    try {
                        return URLDecoder.decode(value, "GBK");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return value;
                    }
                }
            }
        } else if (url.toLowerCase().contains("google")) {
            String value = getParameter(url, "q");
            if (!StringUtil.isNull(value)) {
                try {
                    return URLDecoder.decode(value, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                    return value;
                }
            }
        }
        return null;
    }

    /**
     * 获取 URL 中 key 的参数值
     */
    public static String getParameter(String url, String key) {
        String queryString = "&" + url.substring(url.indexOf("?") + 1);
        String substring = queryString.substring(queryString.indexOf("&" + key) + key.length() + 2);
        if (!substring.contains("&")) {
            return substring;
        }
        return substring.substring(0, substring.indexOf("&"));
    }

    /**
     * 对字符串进行MD5加密
     *
     * @param str
     * @return String
     */
    public static String md5Encryption(String str) {
        String newStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base = new BASE64Encoder();
            newStr = base.encode(md5.digest(str.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newStr;
    }

    /*
    * 解析Email。
    * SimpleMailMessage 可以设置多个收件人、抄送人、暗送人。设置多个收件人时，必须使用数组形式设置。而用户输入的以“;”、“,”或空格隔开的多个Email地址，
    * 并不能直接当作多个邮件地址传入 SimpleMailMessage 中，需要做下处理。
    * */
    public static String[] parseEmail(String s) {
        if (StringUtil.isNull(s))
            return new String[]{};  //如果空，则返回0个Email地址
        s = s.replace(";", " ").replace(",", " ");
        return s.split("\\s");  //将字符串以空格为边界，分割为多个Email
    }

    /*
    * 将日期格式转换为字符串形式，格式如：2004-12-16 17:24:27
    * */
    public static String toDateString(java.util.Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }

    /*
     * 将字符串日期格式转换为日期格式，字符串如：2004-12-16 17:24:27
     * */
    public static java.util.Date toDate(String date) throws Exception {
        String fmt = null;
        if (date.length() == 19)
            fmt = "yyyy-MM-dd HH:mm:ss";
        else if (date.length() == 10)
            fmt = "yyyy-MM-dd";
        else if (date.length() == 16)
            fmt = "yyyy-MM-dd HH:mm";
        else
            throw new Exception(MessageFormat.format("{0} 不是日期格式字符串，支持的日期格式长度有：10、16、19", date));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fmt);
        return simpleDateFormat.parse(date);  //throws ParseException
    }
}
